﻿using blog.Dao;
using blog.Model;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Data.SqlClient;

namespace blog.Controllers
{
    [Route("api/blog/[action]")]
    [ApiController]
    public class BlogController : Controller
    {
  

        [HttpGet]
        public Result<Blog> SelectBlogById(string id)
        {
            Result<Blog> res = new Result<Blog>();
            Blog blog = new Blog();
            List<Content> contents = new List<Content>();
            List<Users> users = new List<Users>();
            string sql = "select content.*,users.username,users.userAvatar from content inner join users on content.userId=users.id where content.id=@id";
            SqlParameter[] parameters =
            {
                new SqlParameter("@id",id),
            };
            //2、调用DataSet通用的查询的方法
            //DataSet ds=DBHelper.GetDataSet(sql,null);
            DataSet ds = DBHelper.GetDataSet(sql, parameters);

            //4、获得DataSet对象中指定的表（学生表）
            DataTable dt = ds.Tables[0];

            //5、遍历表中的每一行，把每行中的各个字段的值依次存入学生对象，添加学生对象到学生列表
            Content content = null;
            Users user = null;
            foreach (DataRow dr in dt.Rows)
            {
                content = new Content();
                content.Id = Convert.ToInt32(dr["id"]);
                content.UserId = Convert.ToInt32(dr["userId"]);
                content.Title = dr["title"].ToString();
                content.ContentMd = dr["contentMd"].ToString();
                content.ContentHtml = dr["contentHtml"].ToString();
                content.Abs = dr["abs"].ToString();
                content.Cover = dr["cover"].ToString();
                content.CreateTime = Convert.ToDateTime(dr["createTime"]);
                contents.Add(content);
                user = new Users();
                user.Username= dr["username"].ToString();
                user.UserAvatar = dr["userAvatar"].ToString();
                users.Add(user);
            }
            res.Code = 200;
            res.Message = "查询成功";
            blog.User = user;
            blog.Content = content;
            res.Data = blog;
            return res;
        }


    }
}
